import React, { useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Form, Input, Button, Alert, Typography, Row, Col, Progress } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, RocketOutlined, UserAddOutlined } from '@ant-design/icons';
import { useAuthStore } from '../store/auth';

const { Title, Text } = Typography;

const RegisterPage: React.FC = () => {
  const [form] = Form.useForm();
  const { register, isLoading, error, clearError, isAuthenticated } = useAuthStore();
  const navigate = useNavigate();

  // 如果已经登录，重定向到仪表板
  useEffect(() => {
    if (isAuthenticated) {
      navigate('/app/dashboard', { replace: true });
    }
  }, [isAuthenticated, navigate]);

  // 清除错误信息当组件卸载时
  useEffect(() => {
    return () => {
      clearError();
    };
  }, [clearError]);

  const handleSubmit = async (values: any) => {
    clearError();
    try {
      const registerData: any = {
        username: values.username.trim(),
        email: values.email.trim(),
        password: values.password,
      };
      
      // 只有当姓名不为空时才传递
      if (values.full_name && values.full_name.trim()) {
        registerData.full_name = values.full_name.trim();
      }
      
      await register(registerData);
    } catch (error) {
      // 错误处理由store管理
    }
  };

  // 计算密码强度
  const getPasswordStrength = (password: string) => {
    if (!password) return 0;
    let strength = 0;
    if (password.length >= 6) strength += 20;
    if (/[a-z]/.test(password)) strength += 20;
    if (/[A-Z]/.test(password)) strength += 20;
    if (/[0-9]/.test(password)) strength += 20;
    if (/[^a-zA-Z0-9]/.test(password)) strength += 20;
    return strength;
  };

  const passwordValue = Form.useWatch('password', form);
  const passwordStrength = getPasswordStrength(passwordValue || '');

  const getStrengthColor = (strength: number) => {
    if (strength < 40) return '#ff4d4f';
    if (strength < 60) return '#faad14';
    if (strength < 80) return '#52c41a';
    return '#1890ff';
  };

  const getStrengthText = (strength: number) => {
    if (strength < 40) return '弱';
    if (strength < 60) return '一般';
    if (strength < 80) return '强';
    return '很强';
  };

  return (
    <>
      <div style={{ minHeight: '100vh', display: 'flex' }}>
        <Row style={{ width: '100%', minHeight: '100vh' }}>
          {/* 左侧紫色渐变背景 */}
          <Col xs={0} md={12} lg={14} xl={16} style={{
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            position: 'relative',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            overflow: 'hidden'
          }}>
            {/* 装饰性几何图形 */}
            <div style={{ position: 'absolute', width: '100%', height: '100%' }}>
              {[...Array(6)].map((_, i) => (
                <div
                  key={i}
                  style={{
                    position: 'absolute',
                    width: `${120 + i * 40}px`,
                    height: `${120 + i * 40}px`,
                    backgroundColor: 'rgba(255, 255, 255, 0.1)',
                    borderRadius: '12px',
                    transform: `rotate(${i * 15}deg)`,
                    top: `${20 + i * 10}%`,
                    left: `${15 + i * 8}%`,
                    animation: `float ${3 + i * 0.5}s ease-in-out infinite alternate`
                  }}
                />
              ))}
            </div>

            {/* 主要内容 */}
            <div style={{ 
              position: 'relative', 
              zIndex: 2, 
              textAlign: 'center',
              color: 'white',
              maxWidth: '400px',
              padding: '0 40px'
            }}>
              <div style={{ marginBottom: '32px' }}>
                <RocketOutlined style={{ fontSize: '48px', marginBottom: '16px' }} />
                <Title level={2} style={{ color: 'white', fontSize: '28px', marginBottom: '8px' }}>
                  星链saas运维系统
                </Title>
              </div>
              
              <Title level={1} style={{ 
                color: 'white', 
                fontSize: '48px', 
                fontWeight: 'bold',
                marginBottom: '24px',
                lineHeight: 1.2
              }}>
                加入我们
              </Title>
              
              <Text style={{ 
                color: 'rgba(255, 255, 255, 0.8)', 
                fontSize: '18px',
                lineHeight: 1.6
              }}>
                创建账号，开始您的运维管理之旅
              </Text>

              {/* 装饰性小圆点 */}
              {[...Array(3)].map((_, i) => (
                <div
                  key={i}
                  style={{
                    position: 'absolute',
                    width: '8px',
                    height: '8px',
                    backgroundColor: 'rgba(255, 255, 255, 0.4)',
                    borderRadius: '50%',
                    top: `${60 + i * 15}%`,
                    right: `${10 + i * 5}%`,
                    animation: `pulse ${2 + i * 0.3}s ease-in-out infinite`
                  }}
                />
              ))}
            </div>
          </Col>

          {/* 右侧注册表单 */}
          <Col xs={24} md={12} lg={10} xl={8} style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '40px',
            backgroundColor: '#fff'
          }}>
            <div style={{ width: '100%', maxWidth: '400px' }}>
              {/* 表单头部 */}
              <div style={{ textAlign: 'right', marginBottom: '40px' }}>
                <Title level={2} style={{ marginBottom: '8px', color: '#262626' }}>
                  账号注册
                </Title>
                <Text type="secondary" style={{ fontSize: '14px' }}>
                  <Link to="/login" style={{ color: '#1890ff', textDecoration: 'none' }}>
                    返回登录 →
                  </Link>
                </Text>
              </div>

              {error && (
                <Alert
                  message={error}
                  type="error"
                  showIcon
                  closable
                  onClose={clearError}
                  style={{ marginBottom: '24px' }}
                />
              )}

              <Form
                form={form}
                name="register"
                onFinish={handleSubmit}
                autoComplete="off"
                size="large"
                layout="vertical"
              >
                <Form.Item
                  name="username"
                  rules={[
                    { required: true, message: '请输入用户名!' },
                    { min: 3, message: '用户名至少3个字符' },
                    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' }
                  ]}
                >
                  <Input
                    prefix={<UserOutlined style={{ color: '#999' }} />}
                    placeholder="请输入用户名"
                    disabled={isLoading}
                    style={{ 
                      borderRadius: '8px',
                      border: '1px solid #e8e8e8',
                      padding: '12px 16px'
                    }}
                  />
                </Form.Item>

                <Form.Item
                  name="email"
                  rules={[
                    { required: true, message: '请输入邮箱地址!' },
                    { type: 'email', message: '请输入有效的邮箱地址!' }
                  ]}
                >
                  <Input
                    prefix={<MailOutlined style={{ color: '#999' }} />}
                    placeholder="请输入邮箱"
                    disabled={isLoading}
                    style={{ 
                      borderRadius: '8px',
                      border: '1px solid #e8e8e8',
                      padding: '12px 16px'
                    }}
                  />
                </Form.Item>

                <Form.Item
                  name="full_name"
                  rules={[
                    { min: 2, message: '姓名至少2个字符' }
                  ]}
                >
                  <Input
                    prefix={<UserAddOutlined style={{ color: '#999' }} />}
                    placeholder="请输入姓名（可选）"
                    disabled={isLoading}
                    style={{ 
                      borderRadius: '8px',
                      border: '1px solid #e8e8e8',
                      padding: '12px 16px'
                    }}
                  />
                </Form.Item>

                <Form.Item
                  name="password"
                  rules={[
                    { required: true, message: '请输入密码!' },
                    { min: 6, message: '密码至少6个字符' },
                    { 
                      pattern: /(?=.*[a-zA-Z])(?=.*\d)/, 
                      message: '密码必须包含字母和数字' 
                    }
                  ]}
                >
                  <Input.Password
                    prefix={<LockOutlined style={{ color: '#999' }} />}
                    placeholder="请输入密码（至少6位）"
                    disabled={isLoading}
                    style={{ 
                      borderRadius: '8px',
                      border: '1px solid #e8e8e8',
                      padding: '12px 16px'
                    }}
                  />
                </Form.Item>

                {passwordValue && (
                  <div style={{ marginBottom: '16px' }}>
                    <div style={{ 
                      display: 'flex', 
                      justifyContent: 'space-between', 
                      marginBottom: '8px' 
                    }}>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        密码强度
                      </Text>
                      <Text 
                        style={{ 
                          fontSize: '12px',
                          color: getStrengthColor(passwordStrength)
                        }}
                      >
                        {getStrengthText(passwordStrength)}
                      </Text>
                    </div>
                    <Progress
                      percent={passwordStrength}
                      strokeColor={getStrengthColor(passwordStrength)}
                      showInfo={false}
                      size="small"
                    />
                  </div>
                )}

                <Form.Item
                  name="confirmPassword"
                  dependencies={['password']}
                  rules={[
                    { required: true, message: '请确认密码!' },
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value || getFieldValue('password') === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error('两次输入的密码不一致!'));
                      },
                    }),
                  ]}
                >
                  <Input.Password
                    prefix={<LockOutlined style={{ color: '#999' }} />}
                    placeholder="请确认密码"
                    disabled={isLoading}
                    style={{ 
                      borderRadius: '8px',
                      border: '1px solid #e8e8e8',
                      padding: '12px 16px'
                    }}
                  />
                </Form.Item>

                <Form.Item style={{ marginBottom: '16px' }}>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={isLoading}
                    style={{ 
                      width: '100%',
                      height: '48px',
                      borderRadius: '8px',
                      fontSize: '16px',
                      fontWeight: 500,
                      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                      border: 'none',
                      boxShadow: '0 4px 12px rgba(102, 126, 234, 0.4)'
                    }}
                  >
                    注册
                  </Button>
                </Form.Item>

                <div style={{ textAlign: 'center' }}>
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    已有账号？
                    <Link to="/login" style={{ color: '#1890ff', marginLeft: '4px' }}>
                      立即登录
                    </Link>
                  </Text>
                </div>
              </Form>

              {/* 注册须知 */}
              <div style={{ 
                marginTop: '40px', 
                padding: '16px', 
                backgroundColor: '#f9f9f9', 
                borderRadius: '8px' 
              }}>
                <Title level={5} style={{ marginBottom: '8px', fontSize: '14px' }}>
                  注册须知
                </Title>
                <Text type="secondary" style={{ fontSize: '12px', lineHeight: 1.5 }}>
                  请使用真实邮箱注册，注册成功后可使用用户名或邮箱登录。密码长度至少6位，建议包含字母和数字。
                </Text>
              </div>
            </div>
          </Col>
        </Row>
      </div>

      {/* CSS动画 */}
      <style>
        {`
          @keyframes float {
            0% { transform: translateY(0px) rotate(0deg); }
            100% { transform: translateY(-10px) rotate(5deg); }
          }
          
          @keyframes pulse {
            0%, 100% { opacity: 0.4; transform: scale(1); }
            50% { opacity: 0.8; transform: scale(1.2); }
          }
        `}
      </style>
    </>
  );
};

export default RegisterPage; 